import AStar from "./AStar";
import MapModel from "./MapModel";


const { ccclass, property } = cc._decorator;

@ccclass
export default class test extends cc.Component {

    @property(cc.EditBox)
    starEdit: cc.EditBox = null;

    @property(cc.EditBox)
    endEdit: cc.EditBox = null;

    @property(cc.EditBox)
    mapEdit: cc.EditBox = null;

    @property(cc.Node)
    mapContent: cc.Node = null;

    @property(cc.Node)
    temp: cc.Node = null;

    start() {

        this.loadMap();
        this.updateMap();
    }

    loadMap() {
        let all = MapModel.mapData[0].length * MapModel.mapData.length;

        for (let i = 0; i < all; i++) {
            if (!this.mapContent.children[i]) {
                let node = cc.instantiate(this.temp);
                node.setParent(this.mapContent);
            }
        }
    }

    updateMap() {
        for (let i in this.mapContent.children) {
            let h = Math.floor(parseInt(i) / MapModel.mapData[0].length);
            let c = parseInt(i) % MapModel.mapData[0].length;
            let mapDataItem = MapModel.mapData[h][c];
            this.mapContent.children[i].children[1].getComponent(cc.Label).string = i;
            if (mapDataItem == 1) {
                this.mapContent.children[i].children[0].color = cc.color(255, 0, 0);
            } else {
                this.mapContent.children[i].children[0].color = cc.color(255, 255, 255);
            }
        }
    }

    showPath(path) {
        for (let i in this.mapContent.children) {
            let h = Math.floor(parseInt(i) / MapModel.mapData[0].length);
            let c = parseInt(i) % MapModel.mapData[0].length;
            let mapDataItem = MapModel.mapData[h][c];


        }

        this.updateMap();

        for (let i in path) {
            let x = path[i].x;
            let y = path[i].y;
            let index = x * MapModel.mapData[0].length + y;
            this.mapContent.children[index].children[0].color = cc.color(255, 255, 0);
        }
    }

    onClickFind() {
        let start = parseInt(this.starEdit.string);
        let end = parseInt(this.endEdit.string);

        let h = Math.floor(start / MapModel.mapData[0].length)
        let c = start % MapModel.mapData[0].length;
        let sPos = { x: h, y: c };


        h = Math.floor(end / MapModel.mapData[0].length)
        c = end % MapModel.mapData[0].length;
        let ePos = { x: h, y: c };

        AStar.getInstance().findPath(sPos, ePos, (path) => {
            this.showPath(path)
            console.log("path = ", path)
        })
    }


    onClickBlock() {

        let blockIndex = parseInt(this.mapEdit.string);
        let h = Math.floor((blockIndex) / MapModel.mapData[0].length);
        let c = (blockIndex) % MapModel.mapData[0].length;
        MapModel.mapData[h][c] = 1;
        this.updateMap();
    }
}
